package com.ckzp.jfinal.weixin.util;

import com.alibaba.fastjson.JSON;
import com.ckzp.core.util.*;
import com.ckzp.core.util.DateUtil;
import com.ckzp.core.util.JwtUtil;
import com.ckzp.core.util.ParamUtil;
import com.ckzp.core.util.StringUtil;
import com.ckzp.jfinal.system.util.SysWorkLogUtil;
import com.ckzp.jfinal.weixin.model.WxMember;
import com.ckzp.weixin.AccessTokenTool;
import com.ckzp.weixin.PageSite;
import com.ckzp.weixin.WxTool;
import com.ckzp.weixin.model.WxUser;
import com.ckzp.weixin.model.WxUserToken;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * Created by 51594 on 2022/9/22.
 */
public class WxUserUtil {

    public static WxUserUtil n() {
        return new WxUserUtil();
    }


    /**
     * @param request
     * @return
     */
    public WxUser initWxUserUnion(HttpServletRequest request) {
        String code = ParamUtil.getString(request, "code", "");
        String state = ParamUtil.getString(request, "state", "");
        String jwt = ParamUtil.getString(request, "jwt", "");
        int user_id = JwtUtil.getUserId(jwt);
        if (user_id == 0) user_id = PageSite.getU_ID(request);
        WxMember u = WxMember.dao.findById(user_id);
        WxUser user = new WxUser();
        if (u == null) {
            if (code.length() > 0 || WxTool.getState().equals(state)) {
                WxUserToken userToken = getWxToken(code);
                String openid = userToken.getOpenid();
                String unionid = userToken.getUnionid();
                String access_token = userToken.getAccess_token();
                if (StrKit.isBlank(openid) && StrKit.isBlank(unionid)) {

                } else {
                    ////////////////////////////////////////
                    user.setUnion_id(unionid);
                    //////////////////////////////
                    WxMember member = null;
                    if (StrKit.notBlank(unionid)) {
                        member = WxMember.dao.findFirst("select * from wx_member where union_id=?", unionid);
                        if (member != null) {
                            member.set("wx_openid", openid).update();
                            user.setWx_openid(member.mod.getStr("wx_openid", ""));
                            user.setUser_id(member.mod.getInt("mem_id", 0));
                            user.setIs_check(1);
                        }
                    }
                    if (StrKit.notBlank(openid) && member == null) {
                        member = WxMember.dao.findFirst("select * from wx_member where wx_openid=?", openid);
                        if (member != null) {
                            member.set("union_id", unionid).update();
                            user.setWx_openid(member.mod.getStr("wx_openid", ""));
                            user.setUser_id(member.mod.getInt("mem_id", 0));
                            user.setIs_check(1);
                        }
                    }
                    if (member == null) {
                        Date createdate = new Date();
                        member = new WxMember();
                        //是否为快照页模式虚拟账号
                        if (userToken.getIs_snapshotuser() != null && userToken.getIs_snapshotuser() == 1) {
                            member.set("snapuser", 1);
                        }
                        member.set("wx_openid", openid)
                                .set("union_id", unionid)
                                .set("create_date", createdate)
                                .set("create_dateint", DateUtil.getYYYYMMDD(createdate))
                                .save();
                        user.setUser_id(member.getInt("mem_id"));
                    }
                    user.setApp_openid(member.mod.getStr("app_openid", ""));
                    user.setWx_openid(openid);
                    user.setIs_check(1);

                    //更新unionid,username,head头象
                    updateSnsUserInfo(openid, access_token);
                    updateUserInfo(openid);//更新是否关注等信息
                }
            }
        } else {
            user.setWx_openid(u.mod.getStr("wx_openid", ""));
            user.setUnion_id(u.mod.getStr("union_id", ""));
            user.setApp_openid(u.mod.getStr("app_openid", ""));
            user.setUser_id(user_id);
            user.setIs_check(1);
        }
        return user;
    }


    /**
     * @param request
     * @return
     */
    public WxUser initWxUser(HttpServletRequest request) {
        String code = ParamUtil.getString(request, "code", "");
        String state = ParamUtil.getString(request, "state", "");
        String jwt = ParamUtil.getString(request, "jwt", "");
        int user_id = JwtUtil.getUserId(jwt);
        if (user_id == 0) user_id = PageSite.getU_ID(request);
        WxMember u = WxMember.dao.findById(user_id);
        WxUser user = new WxUser();
        if (u == null) {
            if (code.length() > 0 || "9981".equals(state)) {
                WxUserToken userToken = getWxToken(code);
                String openid = userToken.getOpenid();
                //////////////////////////////
                if (openid != null) {
                    WxMember member = WxMember.dao.findFirst("select * from wx_member where wx_openid=?", openid);
                    if (member != null) {
                        member.set("wx_openid", openid).update();
                        user.setWx_openid(member.mod.getStr("wx_openid", ""));
                        user.setUser_id(member.mod.getInt("mem_id", 0));
                    } else {
                        member = new WxMember().set("wx_openid", openid);
                        Date cdate = new Date();
                        int yymmdd = DateUtil.getYYYYMMDD(cdate);
                        member.set("mem_ip", ClientUtil.getIp(request));
                        member.set("c_date", cdate);
                        member.set("c_dateint", yymmdd);
                        member.save();
                        user.setWx_openid(openid);
                        user.setUser_id(member.getInt("mem_id"));
                    }
                }
                /////////////////////////////////////////////
                user.setIs_check(1);
            }
        } else {
            user.setWx_openid(u.mod.getStr("wx_openid", ""));
            user.setUser_id(user_id);
            user.setIs_check(1);
        }
        return user;
    }

    /**
     * 根据 CODE取得用户的OPENID
     *
     * @param code
     * @return
     */
    public WxUserToken getWxToken(String code) {
        String appid = WxTool.getAppID();
        String appsecret = WxTool.getAppSecret();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + appid + "&secret=" + appsecret + "&code=" + code + "" +
                "&grant_type=authorization_code";
        String result = HttpKit.get(url);
        Object o = JSON.parseObject(result, WxUserToken.class);
        if (o instanceof WxUserToken) {
            return (WxUserToken) o;
        } else {
            return new WxUserToken();
        }
    }


    /**
     * https://developers.weixin.qq.com/doc/offiaccount/User_Management/Get_users_basic_information_UnionID.html
     *
     * @param openid
     * @return
     */
    public static String getUserUnionId(String openid) {
        String ACCESS_TOKEN = AccessTokenTool.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + ACCESS_TOKEN + "&openid=" + openid + "&lang=zh_CN";
        String result = HttpKit.get(url);
        Map m = JSON.parseObject(result, Map.class);
        return StringUtil.getString(m, "unionid", "");
    }

    /**
     * @param wx_openid
     * @return
     */
    public int updateSnsUserInfo(String wx_openid, String access_token) {
        Map userinfo = WxTool.getSnsUserInfo(wx_openid, access_token);
        return updateUserInfo(wx_openid, userinfo);
    }


    /**
     * @param wx_openid
     * @return
     */
    public int updateUserInfo(String wx_openid, Map userinfo) {
        WxMember member = WxMember.dao.findFirst("select * from wx_member where wx_openid=?", wx_openid);
        int subscribe = 0;
        long subscribe_time = 0;
        String unionid = null, nickname, headimgurl;
        if (userinfo != null) {
            subscribe = StringUtil.getInt(userinfo, "subscribe");
            unionid = StringUtil.getString(userinfo, "unionid");
            headimgurl = StringUtil.getString(userinfo, "headimgurl");
            nickname = StringUtil.getString(userinfo, "nickname");
            subscribe_time = StringUtil.getLong(userinfo, "subscribe_time");
            if (member == null && StrKit.notBlank(unionid)) {
                member = WxMember.dao.findFirst("select * from wx_member where union_id=?", unionid);
            }
            if (member != null) {
                member.set("wx_openid", wx_openid);
                if (subscribe == 1 && StrKit.notBlank(unionid)) {
                    member.set("union_id", unionid).set("sub_tag", 1);
                    if (subscribe_time > 0) {
                        Date sub_date = new Date(subscribe_time);
                        int dateint = DateUtil.getYYYYMMDD(sub_date);
                        member.set("sub_tag", 1).set("sub_date", sub_date).set("sub_dateint", dateint);
                    }
                }
                if (StrKit.notBlank(nickname)) member.set("user_nick", nickname);
                if (StrKit.notBlank(headimgurl)) member.set("user_head", headimgurl);
                member.update();
            }
        }
        if (member == null) {
            member = new WxMember().set("wx_openid", wx_openid).set("sub_tag", subscribe);
            if (StrKit.notBlank(unionid)) member.set("union_id", unionid);
            member.save();
        }
        return member.getInt("mem_id");
    }

    /**
     * @param wx_openid
     * @return
     */
    public int updateUserInfo(String wx_openid) {
        Map userinfo = WxTool.getUserInfo(wx_openid);
        return updateUserInfo(wx_openid, userinfo);
    }

    public static void main(String[] arg) {
        String s = "null";
        System.out.println(StrKit.notBlank(s));
    }
}